#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This's user service
# -- 
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2017年9月26日 00:29:29
# ---------------------------------------------------------

import json
import requests
from requests import ConnectTimeout, Timeout
from files.enums import CodeEnum
from files.logs import Logger
from files.response import Result
from files.tools import ConfigUtils


class UserService(object):
    """
        user service\n
        -- user login method\n
        :param _log data logs
    """
    _log = Logger.log();

    def __init__(self):
        self.__conf = ConfigUtils();
        self.__result = Result(CodeEnum.SUCCESS.value, "请求成功", None);

    def login(self, userName, password):
        self._log.info("user login info: {} - {}".format(userName, password));
        try:
            loginRequestHost = self.__conf.readConfig("login_request_host");
            requests.get(loginRequestHost, timeout=0.8);
            loginUrl = loginRequestHost + self.__conf.readConfig("login_url");
            # Serialize ``obj`` to a JSON formatted ``str``. -- json.dumps
            loginParams = json.dumps({"phoneNumber": userName, "password": password});
            headers = {"Content-Type": "application/json;charset=UTF-8"};
            loginRequest = requests.post(loginUrl, loginParams, headers=headers);
            self._log.info("This's login thread ：%s", loginRequest);
            # Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. -- json.loads
            self.__result.t = json.loads(loginRequest.text);
            return self.__result;
        except ConnectTimeout as e:
            self._log.error("服务器请求连接失败...%s", e);
            self.__result.code = CodeEnum.CONNECT_FAIL.value;
            self.__result.msg = "服务器请求连接失败";
            return self.__result;
        except Timeout as e:
            self._log.error("服务器请求连接超时...%s", e);
            self.__result.code = CodeEnum.CONNECT_TIMEOUT.value;
            self.__result.msg = "服务器请求连接超时";
            return self.__result;
